package com.touzi.servlets;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.touzi.beans.dbs.chanpin.Chanpin;
import com.touzi.beans.dbs.dingdan.Dingdan;
import com.touzi.beans.dbs.fenhong.Fenhong;
import com.touzi.beans.dbs.fenhong.NewFenhong;
import com.touzi.beans.dbs.liushui.NewLiushui;
import com.touzi.beans.dbs.users.ChangeKeyong;
import com.touzi.beans.dbs.users.User;
import com.touzi.beans.dbs.yongjin.NewYongjin;
import com.touzi.constants.DbCons;
import com.touzi.mapper.*;
import com.touzi.proconfig.AliConfig;
import com.touzi.proconfig.ProjectConfig;
import com.touzi.utils.FenhongUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@WebServlet(name = "AliNotifyServlet")
public class AliNotifyServlet extends BaseServlet {
    private static String CLASS_NAME = "com.touzi.servlets.AliNotifyServlet";

    /**
     * 支付宝的付款异步通知
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private void response(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //TRADE_SUCCESS
        String trade_status = request.getParameter("trade_status");
        //如果不是支付成功类型则忽略，不处理
        if (!(trade_status.equals("TRADE_SUCCESS")) || trade_status == null) {
            ProjectConfig.printMyDebug(CLASS_NAME, trade_status + " ignored");
            return;
        }

        //订单号 15264389454942719145
        String out_trade_no = request.getParameter("out_trade_no");
        String userid = out_trade_no.substring(13);
        String gmt_payment = request.getParameter("gmt_payment");
        String buyer_pay_amount = request.getParameter("buyer_pay_amount");

        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AliConfig.ALIPAY_PUBLIC_KEY, AliConfig.CHARSET, "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        ProjectConfig.printMyDebug(CLASS_NAME, verify_result + " ignored " + out_trade_no);
        //如果购买成功，更新订单状态，添加流水，添加分红计划表,佣金表
        response.getWriter().write("hello");
        if (verify_result) {
            //如果订单已经标记为付款成功则返回
            SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
            DingdanMapper dingdanMapper = sqlSession.getMapper(DingdanMapper.class);
            Dingdan thisDingdan = dingdanMapper.getAdingdByNo(out_trade_no);
            if ((thisDingdan != null) && (thisDingdan.chenggong.equals("yes"))) {
                sqlSession.close();
                response.getWriter().write("success");
                logger.info("订单已经成功，返回消息!");
                return;
            }

            Map<String, String> updatetable = new HashMap<>();
            updatetable.put("fukuanshijian", gmt_payment);
            updatetable.put("dingdanhao", out_trade_no);


            //更新订单状态和添加流水
            LiushuiMapper liushuiMapper = sqlSession.getMapper(LiushuiMapper.class);
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            YongjinMapper yongjinMapper = sqlSession.getMapper(YongjinMapper.class);
            User yonghu = userMapper.findUserByID(Integer.parseInt(userid)); //用户本人
            NewLiushui liushui = new NewLiushui(Integer.parseInt(userid), Float.parseFloat(buyer_pay_amount),
                    "购买付款", Integer.parseInt(yonghu.tuijianren));

            liushuiMapper.insertANewReco(liushui);
            dingdanMapper.updateDDSucc(updatetable);
            userMapper.updateCousumedYesByDianhua(yonghu.dianhua);

            ChanpinMapper chanpinMapper = sqlSession.getMapper(ChanpinMapper.class);
            Chanpin chanpin = chanpinMapper.findCPByDdh(out_trade_no);
            //减去一个库存
            chanpinMapper.jianAChanpin(chanpin.id);

            //创建分红计划
            FenhongMapper fenhongMapper = sqlSession.getMapper(FenhongMapper.class);
            List<NewFenhong> fenhongs = FenhongUtils.getList(Integer.parseInt(userid), out_trade_no, Integer.parseInt(chanpin.fenhongcishu),
                    Float.parseFloat(chanpin.fenhong), Integer.parseInt(chanpin.fenhongzhouqi));
            fenhongMapper.addFenhong(fenhongs);

            //创建佣金
            User yiji = null;
            User erji = null;
            User sanji = null;
            User siji = null;
            User wuji = null;
            User liuji = null;
            User qiji = null;
            User baji = null;
            User jiuji = null;
            User shiji = null;
            User shiyiji = null;
            User shierji = null;
            User shisanji = null;
            yiji = userMapper.findUserByID(Integer.parseInt(yonghu.tuijianren));  //一级推荐人
            if (yiji != null) {
                erji = userMapper.findUserByID(Integer.parseInt(yiji.tuijianren));  //二级推荐人
            }
            if (erji != null) {
                sanji = userMapper.findUserByID(Integer.parseInt(erji.tuijianren));  //三级推荐人
            }
            if (sanji != null) {
                siji = userMapper.findUserByID(Integer.parseInt(sanji.tuijianren));  //三级推荐人
            }
            if (siji != null) {
                wuji = userMapper.findUserByID(Integer.parseInt(siji.tuijianren));  //三级推荐人
            }
            if (wuji != null) {
                liuji = userMapper.findUserByID(Integer.parseInt(wuji.tuijianren));  //三级推荐人
            }
            if (liuji != null) {
                qiji = userMapper.findUserByID(Integer.parseInt(liuji.tuijianren));  //三级推荐人
            }
            if (qiji != null) {
                baji = userMapper.findUserByID(Integer.parseInt(qiji.tuijianren));  //三级推荐人
            }
            if (baji != null) {
                jiuji = userMapper.findUserByID(Integer.parseInt(baji.tuijianren));  //三级推荐人
            }
            if (jiuji != null) {
                shiji = userMapper.findUserByID(Integer.parseInt(jiuji.tuijianren));  //三级推荐人
            }
            if (shiji != null) {
                shiyiji = userMapper.findUserByID(Integer.parseInt(shiji.tuijianren));  //三级推荐人
            }
            if (shiyiji != null) {
                shierji = userMapper.findUserByID(Integer.parseInt(shiyiji.tuijianren));  //三级推荐人
            }
            if (shierji != null) {
                shisanji = userMapper.findUserByID(Integer.parseInt(shierji.tuijianren));  //三级推荐人
            }

            float yijiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.yiYongjin;
            float erjiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.erYongjin;
            float sanjiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.sanYongjin;
            float sijiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.sijiYongjin;
            float wujiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.wujiYongjin;
            float liujiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.liujiYongjin;
            float qijiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.qijiYongjin;
            float bajiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.bajiYongjin;
            float jiujiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.jiujiYongjin;
            float shijiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.shijiYongjin;
            float shiyijiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.shiyijiYongjin;
            float shierjiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.shierjiYongjin;
            float shisanjiyongjin = Float.parseFloat(buyer_pay_amount) * ProjectConfig.shisanjiYongjin;


            if (yiji != null) {
                ChangeKeyong yijibianhua = new ChangeKeyong(yiji.dianhua, yijiyongjin);
                userMapper.addKeyong(yijibianhua);
                NewYongjin yijijilu = new NewYongjin(yiji.id, yonghu.id, out_trade_no, 1, yijiyongjin);
                yongjinMapper.insertANewReco(yijijilu);
            }

            if (erji != null) {
                ChangeKeyong erjibianhua = new ChangeKeyong(erji.dianhua, erjiyongjin);
                userMapper.addKeyong(erjibianhua);
                NewYongjin erjijilu = new NewYongjin(erji.id, yonghu.id, out_trade_no, 2, erjiyongjin);
                yongjinMapper.insertANewReco(erjijilu);
            }

            if (sanji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(sanji.dianhua, sanjiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(sanji.id, yonghu.id, out_trade_no, 3, sanjiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (siji != null) {
                ChangeKeyong sijibianhua = new ChangeKeyong(sanji.dianhua, sijiyongjin);
                userMapper.addKeyong(sijibianhua);
                NewYongjin sanjijilu = new NewYongjin(siji.id, yonghu.id, out_trade_no, 4, sijiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (wuji != null) {
                ChangeKeyong wujibianhua = new ChangeKeyong(wuji.dianhua, wujiyongjin);
                userMapper.addKeyong(wujibianhua);
                NewYongjin sanjijilu = new NewYongjin(wuji.id, yonghu.id, out_trade_no, 5, wujiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (liuji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(liuji.dianhua, liujiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(liuji.id, yonghu.id, out_trade_no, 6, liujiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (qiji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(qiji.dianhua, qijiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(qiji.id, yonghu.id, out_trade_no, 7, qijiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (baji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(baji.dianhua, bajiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(baji.id, yonghu.id, out_trade_no, 8, bajiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (jiuji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(jiuji.dianhua, jiujiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(jiuji.id, yonghu.id, out_trade_no, 9, jiujiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (shiji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(shiji.dianhua, shijiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(shiji.id, yonghu.id, out_trade_no, 10, shijiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (shiyiji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(shiyiji.dianhua, shiyijiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(shiyiji.id, yonghu.id, out_trade_no, 11, shiyijiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (shierji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(shierji.dianhua, shierjiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(shierji.id, yonghu.id, out_trade_no, 12, shierjiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            if (shisanji != null) {
                ChangeKeyong sanjibianhua = new ChangeKeyong(shisanji.dianhua, shisanjiyongjin);
                userMapper.addKeyong(sanjibianhua);
                NewYongjin sanjijilu = new NewYongjin(shisanji.id, yonghu.id, out_trade_no, 13, shisanjiyongjin);
                yongjinMapper.insertANewReco(sanjijilu);
            }

            sqlSession.commit();
            sqlSession.close();
            response.getWriter().write("success");
        } else {
            response.getWriter().write("fail");
        }
    }

}
